package com.handle.http;

import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

/**
 * @author linyu.dai
 * @project rpc
 * @description
 * @creat 2022/11/29 21:07:02
 */
public class HttpBaseHandle {

    public static DefaultFullHttpResponse error500(){
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        byte[] bytes = "<h1>500 server error </h1>".getBytes();
        response.content().writeBytes(bytes);
        //告诉http响应的长度 防止浏览器转圈
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH,bytes.length);
        return response;
    }

    public static DefaultFullHttpResponse error400(){
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
        byte[] bytes = "<h1>400 request error </h1>".getBytes();
        response.content().writeBytes(bytes);
        //告诉http响应的长度 防止浏览器转圈
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH,bytes.length);
        return response;
    }

    public static DefaultFullHttpResponse error404(){
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
        byte[] bytes = "<h1>404 not frond </h1>".getBytes();
        response.content().writeBytes(bytes);
        //告诉http响应的长度 防止浏览器转圈
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH,bytes.length);
        return response;
    }

    public static DefaultFullHttpResponse success(byte[] body, String type){
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        response.content().writeBytes(body);
        //告诉http响应的长度 防止浏览器转圈
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH,body.length);
        //设置json返回
        response.headers().set(HttpHeaderNames.CONTENT_TYPE,type);
        return response;
    }
}
